package backing;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

import javax.faces.application.FacesMessage;
import javax.faces.bean.ManagedBean;
import javax.faces.bean.ViewScoped;
import javax.faces.component.UIComponent;
import javax.faces.context.FacesContext;
import javax.faces.validator.ValidatorException;
import javax.servlet.http.Part;

@ManagedBean
@ViewScoped
public class UploadPage {
	
	private List<Part> listaAnexo;
    private Part uploadedFile;
    private String fileContent;
    
    public void validateFile(FacesContext ctx, UIComponent comp, Object value) {    	
    	
        List<FacesMessage> msgs = new ArrayList<FacesMessage>();
        Part file = (Part)value;
        
        if (file.getSize() > 1000000) {
            msgs.add(new FacesMessage("file too big"));
        }
        if (!msgs.isEmpty()) {
            throw new ValidatorException(msgs);
        }
    }

    public void uploadFile() {
        try {
               // Exibir em um Text Area
        	// fileContent = new Scanner(uploadedFile.getInputStream()).useDelimiter("\\A").next();
        	//uploadedFile.write("C:\\" + getFileName(uploadedFile)+"222");
        	
        	listaAnexo.add(uploadedFile);
        	System.out.println("Tamanho da lista: " + listaAnexo.size());

        } catch (Exception e) {
            FacesMessage msg = new FacesMessage(FacesMessage.SEVERITY_ERROR,
                                                "Erro para carregar arquivo. Cod. errp: " + e,
                                                null);            
            FacesContext.getCurrentInstance().addMessage(null, msg);
        }
    }
    
    public static String getFileName(Part part){
    	for (String cd : part.getHeader("content-disposition").split(";")){
    		if (cd.trim().startsWith("filename")){
    			String filename = cd.substring(cd.indexOf('=') + 1).trim().replace("\"","");
    			return filename.substring(filename.lastIndexOf('/') + 1).substring(filename.indexOf('\\') + 1);
    		}
    	}
    	return null;
    }

    public Part getUploadedFile() {
        return uploadedFile;
    }

    public void setUploadedFile(Part uploadedFile) {
        this.uploadedFile = uploadedFile;
    }

    public String getFileContent() {
        return fileContent;
    }

	public List<Part> getListaAnexo() {
		return listaAnexo;
	}

	public void setListaAnexo(List<Part> listaAnexo) {
		this.listaAnexo = listaAnexo;
	}
    
    

}